import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:waterfall_flow/waterfall_flow.dart';
import 'package:xvideos/hj_model/cartoon_media_info.dart';
import 'package:xvideos/hj_page/cartoon_business/acg_widget_item.dart';
import 'package:xvideos/hj_page/home_business/home_cell_style/video_simple_cell_widget.dart';
import 'package:xvideos/hj_page/home_business/search_page/video_all_type_logic.dart';
import '../../../hj_model/home/home_video_library.dart';
import '../../../hj_model/home/module_detail_model.dart';
import '../../../hj_model/video_model.dart';
import '../../../tools_base/appbar/base_app_bar.dart';
import '../../../tools_base/loading/l_error_widget.dart';
import '../../../tools_base/loading/loading_center_widget.dart';
import '../../../tools_base/refresh/pull_refresh.dart';
import '../../cartoon_business/search_tuji_cell.dart';
import '../../community_business/widget/community_post_widget.dart';

class VideoAllTypePage extends StatelessWidget {
  const VideoAllTypePage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GetBuilder(
      init: VideoAllTypeLogic(),
      builder: (logic) {
        return Scaffold(
          appBar: BaseAppBar(title: '片库'),
          body: Obx(
            () {
              if (logic.isInitData.value) {
                return LoadingCenterWidget();
              } else if (logic.homeVideoLibrary?.isNotEmpty != true) {
                return CErrorWidget(
                  retryOnTap: () {
                    logic.reloadMenuData();
                  },
                );
              } else {
                return pullYsRefresh(
                  onInit: (ctr) => logic.refreshController = ctr,
                  onLoading: (_) => logic.loadMoreData(),
                  onRefresh: (_) => logic.refreshData(),
                  child: CustomScrollView(
                    slivers: [
                      SliverToBoxAdapter(
                        child: Column(
                          children: [
                            _buildItemMenuWidget("分类", logic.homeVideoLibrary?.canvas, logic.firstSelectedType, (data) {
                              if (logic.firstSelectedType?.isACG != data.isACG) {
                                logic.thirdSelectedType = null;
                              }
                              if (logic.firstSelectedType != data) {
                                logic.firstSelectedType = data;
                              } else {
                                logic.firstSelectedType = null;
                              }
                              logic.searchVideoList?.clear();
                              logic.menuExchangeEvent();
                            }),
                            _buildItemMenuWidget("排序", logic.homeVideoLibrary?.orderBy, logic.secondSelectedType,
                                (data) {
                              if (logic.secondSelectedType != data) {
                                logic.secondSelectedType = data;
                              } else {
                                logic.secondSelectedType = null;
                              }
                              logic.menuExchangeEvent();
                            }),
                            _buildTagMenuWidget("标签", logic.tags, logic.thirdSelectedType, (data) {
                              if (logic.thirdSelectedType != data) {
                                logic.thirdSelectedType = data;
                              } else {
                                logic.thirdSelectedType = null;
                              }
                              logic.menuExchangeEvent();
                            }),
                            _buildItemMenuWidget("价格", logic.homeVideoLibrary?.paymentType, logic.forthSelectedType,
                                (data) {
                              if (logic.forthSelectedType != data) {
                                logic.forthSelectedType = data;
                              } else {
                                logic.forthSelectedType = null;
                              }
                              logic.menuExchangeEvent();
                            }),
                            _buildItemMenuWidget("时间", logic.homeVideoLibrary?.timeType, logic.fivthSelectedType,
                                (data) {
                              if (logic.fivthSelectedType != data) {
                                logic.fivthSelectedType = data;
                              } else {
                                logic.fivthSelectedType = null;
                              }
                              logic.menuExchangeEvent();
                            }),
                          ],
                        ),
                      ),
                      _buildTableContent(logic),
                    ],
                  ),
                );
              }
            },
          ),
        );
      },
    );
  }

  Widget _buildConditionItem(String? title, bool isSelected) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 6),
      margin: EdgeInsets.only(right: 5),
      alignment: Alignment.centerLeft,
      child: Text(
        title ?? "",
        style: TextStyle(
          color: isSelected ? Color(0xffE1351F) : Color(0x8CFFFFFF),
          fontSize: 14,
          fontWeight: isSelected ? FontWeight.w500 : FontWeight.w400,
        ),
      ),
    );
  }

  Widget _buildTitleItem(String? typeName) {
    return Text(
      '${typeName ?? ""}',
      style: TextStyle(
        color: Colors.white,
        fontSize: 14,
        fontWeight: FontWeight.w500,
      ),
    );
  }

  Widget _buildTableContent(VideoAllTypeLogic logic) {
    if (logic.searchVideoList == null && logic.searchACGList == null) {
      return SliverToBoxAdapter(
        child: SizedBox(
          height: 300,
          child: LoadingCenterWidget(),
        ),
      );
    } else if (logic.searchVideoList?.isNotEmpty != true && logic.searchACGList?.isNotEmpty != true) {
      return SliverToBoxAdapter(
        child: SizedBox(
          height: 300,
          child: CErrorWidget(
            retryOnTap: () {
              logic.reloadData();
            },
          ),
        ),
      );
    } else {
      String typeName = logic.firstSelectedType?.name ?? "";
      if (typeName == "帖子") {
        return SliverList(
          delegate: SliverChildBuilderDelegate(
            (context, index) {
              return CommunityPostWidget(
                videoModel: logic.searchVideoList![index],
                videoModels: logic.searchVideoList,
              );
            },
            childCount: logic.searchVideoList?.length ?? 0,
          ),
        );
      }
      if (typeName == "图集") {
        return SliverPadding(
          padding: const EdgeInsets.fromLTRB(12, 12, 12, 0),
          sliver: SliverWaterfallFlow(
            gridDelegate: const SliverWaterfallFlowDelegateWithFixedCrossAxisCount(
              crossAxisCount: 3,
              crossAxisSpacing: 6,
              mainAxisSpacing: 12,
            ),
            delegate: SliverChildBuilderDelegate(
              (BuildContext c, int index) {
                var videoModel = logic.searchVideoList![index];
                var ratio = 111 / 190;
                return AspectRatio(
                  aspectRatio: ratio,
                  child: SearchTujiCell(videoModel: videoModel, textline: 1),
                );
              },
              childCount: logic.searchVideoList?.length ?? 0,
            ),
          ),
        );
      }
      if (typeName == "抖音" || logic.firstSelectedType?.key == "sp") {
        return SliverPadding(
          padding: const EdgeInsets.fromLTRB(12, 12, 12, 0),
          sliver: SliverWaterfallFlow(
            gridDelegate: const SliverWaterfallFlowDelegateWithFixedCrossAxisCount(
              crossAxisCount: 3,
              crossAxisSpacing: 6,
              mainAxisSpacing: 12,
            ),
            delegate: SliverChildBuilderDelegate(
              (BuildContext c, int index) {
                var videoModel = logic.searchVideoList![index];
                var ratio = 111 / 190;
                return AspectRatio(
                    aspectRatio: ratio,
                    child: VideoSimpleCellWidget(
                      videoModel: videoModel,
                      textLines: 1,
                    ));
              },
              childCount: logic.searchVideoList?.length ?? 0,
            ),
          ),
        );
      } else if (typeName == "动漫" || typeName == "漫画") {
        return SliverPadding(
          padding: EdgeInsets.fromLTRB(12, 12, 12, 0),
          sliver: SliverGrid(
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 3,
              mainAxisSpacing: 12.0,
              crossAxisSpacing: 6,
              childAspectRatio: 111 / 190,
            ),
            delegate: SliverChildBuilderDelegate(
              (context, index) {
                CartoonMediaInfo videoItem = logic.searchACGList![index];
                return AcgItemWidget(info: videoItem);
              },
              childCount: logic.searchACGList?.length ?? 0,
            ),
          ),
        );
      } else {
        return SliverPadding(
          padding: EdgeInsets.fromLTRB(12, 12, 12, 0),
          sliver: SliverGrid(
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 2,
              mainAxisSpacing: 12.0,
              crossAxisSpacing: 6,
              childAspectRatio: 168 / 154,
            ),
            delegate: SliverChildBuilderDelegate(
              (context, index) {
                VideoModel videoItem = logic.searchVideoList![index];
                return VideoSimpleCellWidget(
                  videoModel: videoItem,
                );
              },
              childCount: logic.searchVideoList?.length ?? 0,
            ),
          ),
        );
      }
    }
  }

  Widget _buildItemMenuWidget(
      String typeName, List<TimeType>? listData, TimeType? selectType, Function(TimeType timeType) callBack) {
    if (selectType == null) {
      selectType = listData?[0];
    }
    return Container(
      height: 40,
      padding: EdgeInsets.only(left: 16),
      child: Row(
        children: [
          _buildTitleItem(typeName),
          SizedBox(width: 12),
          Expanded(
            child: ListView.builder(
              itemCount: listData?.length ?? 0,
              scrollDirection: Axis.horizontal,
              padding: EdgeInsets.symmetric(vertical: 8),
              itemBuilder: (context, index) {
                TimeType data = listData![index];
                bool isSelected = selectType?.name == data.name;
                return InkWell(
                  onTap: () async {
                    callBack.call(data);
                  },
                  child: _buildConditionItem(data.name, isSelected),
                );
              },
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildTagMenuWidget(
      String typeName, List<Tags>? listData, Tags? selectType, Function(Tags timeType) callBack) {
    if (selectType == null) {
      selectType = listData?[0];
    }
    return Container(
      height: 40,
      padding: EdgeInsets.only(left: 16),
      child: Row(
        children: [
          _buildTitleItem(typeName),
          SizedBox(width: 12),
          Expanded(
            child: ListView.builder(
              itemCount: listData?.length ?? 0,
              scrollDirection: Axis.horizontal,
              padding: EdgeInsets.symmetric(vertical: 8),
              itemBuilder: (context, index) {
                Tags data = listData![index];
                bool isSelected = selectType?.name == data.name;
                return GestureDetector(
                  onTap: () async {
                    callBack.call(data);
                  },
                  child: _buildConditionItem(data.name, isSelected),
                );
              },
            ),
          ),
        ],
      ),
    );
  }
}
